package com.stn.zjx.givingtreasure.activity.set;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.stn.zjx.givingtreasure.R;
import com.stn.zjx.givingtreasure.activity.UserLoginActivity;
import com.stn.zjx.givingtreasure.application.StnApp;
import com.stn.zjx.givingtreasure.base.BaseActivity;
import com.stn.zjx.givingtreasure.domain.StatusDomain;
import com.stn.zjx.givingtreasure.domain.UserProfileDomain;
import com.stn.zjx.givingtreasure.event.GoLoginEvent;
import com.stn.zjx.givingtreasure.event.NetWorkEvent;
import com.stn.zjx.givingtreasure.net.BaseApi;
import com.stn.zjx.givingtreasure.net.impl.QQWeixinNetImpl;
import com.stn.zjx.givingtreasure.net.impl.UserNetImpl;
import com.stn.zjx.givingtreasure.service.UserService;
import com.stn.zjx.givingtreasure.table.User;
import com.tencent.connect.UserInfo;
import com.tencent.connect.common.Constants;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.vondear.rxtools.RxActivityTool;
import com.vondear.rxtools.RxNetTool;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Objects;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class UserRelationSetActivity extends BaseActivity {


    @BindView(R.id.back_bt)
    RelativeLayout backBt;
    @BindView(R.id.action_title)
    TextView actionTitle;
    @BindView(R.id.web_title)
    TextView webTitle;
    @BindView(R.id.action_add_bt)
    RelativeLayout actionAddBt;
    @BindView(R.id.action_refresh)
    RelativeLayout actionRefresh;
    @BindView(R.id.exit)
    RelativeLayout exit;
    @BindView(R.id.sure_bt)
    TextView sureBt;
    @BindView(R.id.phone_iv)
    ImageView phoneIv;
    @BindView(R.id.go_phone)
    RelativeLayout goPhone;
    @BindView(R.id.wx_iv)
    ImageView wxIv;
    @BindView(R.id.go_wx)
    RelativeLayout goWx;
    @BindView(R.id.qq_iv)
    ImageView qqIv;
    @BindView(R.id.go_qq)
    RelativeLayout goQq;
    @BindView(R.id.phone_status)
    TextView phoneStatus;
    @BindView(R.id.wx_status)
    TextView wxStatus;
    @BindView(R.id.qq_status)
    TextView qqStatus;
    Dialog no_relation_dialog;
    View  norelation_cancel;
    View norelation_sure;
    @Override
    public void networkStatus(NetWorkEvent netWorkEvent) {

    }

    @Override
    public void initComponent() {
        actionTitle.setText(getString(R.string.associated_account));
        no_relation_dialog=new Dialog(this);
        Objects.requireNonNull(no_relation_dialog.getWindow()).setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        no_relation_dialog.setContentView(R.layout.dialog_user_is_sure);
         norelation_cancel=no_relation_dialog.findViewById(R.id.cancel_bt);
        norelation_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                no_relation_dialog.dismiss();
            }
        });
        norelation_sure= no_relation_dialog.findViewById(R.id.sure_bt);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_relation);
        ButterKnife.bind(this);
        initComponent();

    }


    @OnClick({R.id.back_bt})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_bt:
                finish();
                break;

        }
    }


    @Override
    protected void onStart() {
        super.onStart();
        initUser();
    }

    public void initUser() {
        if (UserService.getInstance(this).getOnlineLoginUser() == null) {
            finish();
            return;
        }
        User userOnline = UserService.getInstance(this).getOnlineLoginUser();
        UserNetImpl.user_getuserprofile_bytoken(userOnline.getToken(), userOnline.getUserId() + "user_getuserprofile_bytoken",
                new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        if (response.isSuccessful() && !isFinishing()) {
                            user_getuserprofile_bytoken(response.body());
                        }
                    }

                    @Override
                    public void onCacheSuccess(Response<String> response) {
                        super.onCacheSuccess(response);
                        if (response.isSuccessful() && !isFinishing()) {
                            user_getuserprofile_bytoken(response.body());
                        }
                    }
                });
    }

    //用户在服务器手机号，密码校验正确
    private void loginSuccess(UserProfileDomain domain) {
        boolean isLogin = UserService.getInstance(this)
                .login(domain.getData());
        if (!isLogin) {
            boolean isExitLogin = UserService.getInstance(this)
                    .exitLogin();
            if (isExitLogin) {
                finish();
            }
        }
    }


    //设置用户资料
    public void user_getuserprofile_bytoken(String result) {
        if (result == null) {
            return;
        }
        Gson gson = new Gson();
        UserProfileDomain domain = gson.fromJson(result.trim(), UserProfileDomain.class);
        switch (domain.getStatus()) {
            case BaseApi.REQUEST_SUCCESS_CODE:
                loginSuccess(domain);
                initLocationUser();
                break;
            case BaseApi.REQUEST_LOGINEXIT_ERROR_CODE:

                break;
            case BaseApi.REQUEST_TOKEN_ERROR_CODE:

                break;
        }

    }

    @SuppressLint({"SetTextI18n", "SimpleDateFormat"})
    public void initLocationUser() {
        User userOnline = UserService.getInstance(this).getOnlineLoginUser();
        if (userOnline == null) {
            return;
        }
        if (TextUtils.isEmpty(userOnline.getUserPhone())) {
          phoneStatus.setText(getString(R.string.no_relation));
          phoneStatus.setTextColor(getResources().getColor(R.color.gray));
            goPhone.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    RxActivityTool.skipActivity(getApplicationContext(),UserPhoneBindActivity.class);
                    no_relation_dialog.dismiss();
                }
            });
        } else {
            phoneStatus.setText(getString(R.string.alreay_relation));
            phoneStatus.setTextColor(getResources().getColor(R.color.red));
            goPhone.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    norelation_sure.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            norelation(0,userOnline.getToken());
                            no_relation_dialog.dismiss();
                        }
                    });
                    no_relation_dialog.show();
                }
            });
        }

        if (TextUtils.isEmpty(userOnline.getUserQqid())) {
            qqStatus.setText(getString(R.string.no_relation));
            qqStatus.setTextColor(getResources().getColor(R.color.gray));
            goQq.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                        qqLogin();
                }
            });
        } else {
            qqStatus.setText(getString(R.string.alreay_relation));
            qqStatus.setTextColor(getResources().getColor(R.color.red));
            goQq.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    norelation_sure.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            norelation(2,userOnline.getToken());
                            no_relation_dialog.dismiss();
                        }
                    });
                    no_relation_dialog.show();
                }
            });
        }
        if (TextUtils.isEmpty(userOnline.getUserWxid())) {
            wxStatus.setText(getString(R.string.no_relation));
            wxStatus.setTextColor(getResources().getColor(R.color.gray));
            goWx.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                         wxlogin();
                }
            });
        } else {
            wxStatus.setText(getString(R.string.alreay_relation));
            wxStatus.setTextColor(getResources().getColor(R.color.red));
            goWx.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    norelation_sure.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            norelation(1,userOnline.getToken());
                            no_relation_dialog.dismiss();
                        }
                    });
                    no_relation_dialog.show();
                }
            });
        }

    }

    public void norelation(Integer type,String token){
        QQWeixinNetImpl
                .qqweixin_third_norelation(type, token, "qqweixin_third_norelation", new StringCallback() {
                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                      showLoading();
                     }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                     dissmissLoading();
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        StatusDomain domain=new Gson().fromJson(response.body(),StatusDomain.class);
                         switch (domain.getStatus()){
                             case BaseApi.REQUEST_SUCCESS_CODE:
                                    finish();
                                 break;
                              default:

                                  break;
                         }
                         showToast(domain.getMessage());
                    }
                });
    }


    //QQ登录
    public void qqLogin() {
        if(!StnApp.tencent.isQQInstalled(this)){
            showToast(getString(R.string.no_install_qq));
        }
        showToast(getString(R.string.loading_open__qq));
        StnApp.tencent.login(this, "all", new QQLoginListener());
    }
    //微信登录
    public void wxlogin() {
        showToast(getString(R.string.loading_open__wexin));
        SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "wxchat_login";
        StnApp.iwxapi.sendReq(req);//执行完毕这句话之后，会在WXEntryActivity回调
    }

    //QQ登录监听
    public class QQLoginListener implements IUiListener {
        @Override
        public void onComplete(Object o) {
            showLoading();
            if (o == null) {
                return;
            }
            JSONObject jo = (JSONObject) o;
            try {
                int ret = jo.getInt("ret");
                if (ret == 0) {
                    String openid = jo.getString("openid");
                    String access_token = jo.getString("access_token");
                    String expires_in = jo.getString("expires_in");
                    StnApp.tencent.setOpenId(openid);
                    StnApp.tencent.setAccessToken(access_token, expires_in);
                    UserInfo qqInfo = new UserInfo(getApplicationContext(), StnApp.tencent.getQQToken());
                    qqInfo.getUserInfo(new QQgetUserListener(openid));
                }
            } catch (JSONException e) {
                e.printStackTrace();
                dissmissLoading();
            }
        }

        @Override
        public void onError(UiError uiError) {
            showToast(getString(R.string.request_please_wait));
        }

        @Override
        public void onCancel() {
        }
    }

    //得到QQ用户信息
    public class QQgetUserListener implements IUiListener {
        String openid = "";

        public QQgetUserListener(String openid) {
            this.openid = openid;
        }

        @Override
        public void onComplete(Object o) {
            if (o == null) {
                return;
            }
            JSONObject jo = (JSONObject) o;
            String path = "";
            String nickname = "";
            String gender = "男";
            try {
                nickname = jo.getString("nickname");
                gender = jo.getString("gender");
                path = jo.getString("figureurl_qq_2");
                GoLoginEvent event=new GoLoginEvent();
                event.loginType=0;
                event.sex=gender;
                event.userAvatar=path;
                event.userNickname=nickname;
                event.id=openid;
                EventBus.getDefault()
                        .post(event);
                dissmissLoading();
            } catch (JSONException e) {
                e.printStackTrace();
                dissmissLoading();
            }
        }

        @Override
        public void onError(UiError uiError) {

        }

        @Override
        public void onCancel() {

        }
    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            //QQ验证登录
            case Constants.REQUEST_LOGIN:

                Tencent.onActivityResultData(requestCode, resultCode, data, new QQLoginListener());
                break;
        }

    }



    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGoLoginEvent(GoLoginEvent event){

        if(!RxNetTool.isAvailable(this)) {
            showToast(getString(R.string.request_networkavailable));
            return;
        }
           User userOnline=UserService.getInstance(getApplicationContext())
                   .getOnlineLoginUser();
        if(userOnline==null){
          return;
        }
        try {
             switch (event.loginType){
                 case 0:
                     relation(event.id,2,userOnline.getToken());
                     break;
                 case 1:
                     relation(event.id,1,userOnline.getToken());
                  break;
             }

        } catch (Exception e) {
            e.printStackTrace();
            showToast(e.getMessage());
        }
    }

    public void relation(String id,Integer type,String token){
        QQWeixinNetImpl
                .qqweixin_third_relation(id,"",type, token, "qqweixin_third_relation", new StringCallback() {
                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        showLoading();
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                        dissmissLoading();
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        StatusDomain domain=new Gson().fromJson(response.body(),StatusDomain.class);
                        switch (domain.getStatus()){
                            case BaseApi.REQUEST_SUCCESS_CODE:
                                initUser();
                                break;
                            default:

                                break;
                        }
                        showToast(domain.getMessage());
                    }
                });
    }

}
